﻿using System.Windows.Forms;

namespace Borg.Framework
{
    internal class SelectComboBoxBinder
    {
        private SelectComboBoxBinder(SlotInfo slot, System.Windows.Forms.ComboBox box)
        {
            Slot = slot;
            Box = box;
        }

        private void Bind()
        {
            BindData();
            SetFormatter();
            BindSelection();
        }

        private void BindData()
        {
            IDataModel<PlugInfo> model = new PluggedPlugsDataModel(Slot);
            Box.DataSource = new DataSourceAdapter<PlugInfo>(model);
        }

        private void BindSelection()
        {
            var binding = CreateSelectionBinding();
            Box.DataBindings.Add(binding);
        }

        public static void BindSlotToBox(SlotInfo slot, System.Windows.Forms.ComboBox box)
        {
            new SelectComboBoxBinder(slot, box).Bind();
        }

        private Binding CreateSelectionBinding()
        {
            return new Binding(
                "SelectedIndex",
                new PlugSelectionController(
                    Slot,
                    SelectExtensionAction.SelectExtension,
                    SelectedPlugProvider.SelectedPlugIndex),
                "SelectedIndex",
                true)
                       {
                           ControlUpdateMode = ControlUpdateMode.OnPropertyChanged,
                           DataSourceUpdateMode = DataSourceUpdateMode.OnPropertyChanged
                       };
        }

        private void SetFormatter()
        {
            var formatter = new PlugFormatter();
            Box.Format += formatter.OnFormat;
        }

        private System.Windows.Forms.ComboBox Box { get; set; }

        private SlotInfo Slot { get; set; }
    }
}

